package com.lm.redis.example;

import redis.clients.jedis.GeoRadiusResponse;
import redis.clients.jedis.GeoUnit;
import redis.clients.jedis.Jedis;
import redis.clients.jedis.params.geo.GeoRadiusParam;

import java.util.List;

public class RedisGeoExample {
    public static void main(String[] args) {
        // 连接 Redis
        Jedis jedis =  new Jedis("192.168.1.181",6379);
        jedis.auth("123456?");

        // 添加用户的地理位置信息 (userId, longitude, latitude)
        jedis.geoadd("users", 116.403963, 39.915119, "user1");  // 北京
        jedis.geoadd("users", 121.473701, 31.230416, "user2");  // 上海
        jedis.geoadd("users", 114.305393, 30.592850, "user3");  // 武汉

        System.out.println("Users' locations added to Redis Geo");



        // 查询北京 (116.403963, 39.915119) 附近 500 公里的用户
        List<GeoRadiusResponse> nearbyUsers = jedis.georadius(
                "users", 116.403963, 39.915119, 500, GeoUnit.FT, // 经纬度与半径
                GeoRadiusParam.geoRadiusParam().withDist().sortAscending()// 结果按距离升序
        );

        for (GeoRadiusResponse user : nearbyUsers) {
            System.out.println("User: " + user.getMemberByString() + ", Distance: " + user.getDistance());
        }
    }
}
